#!/usr/bin/env python

import httplib2
import logging
import os
import pickle

from apiclient.discovery import build
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp.util import login_required
from oauth2client.appengine import StorageByKeyName

import wsgiref.handlers

from microsyndutils import UserAccount
from microsyndutils import Shout

class BuzzClient():
    @staticmethod
    def post(message):
        user = users.get_current_user()
        credentials = StorageByKeyName(
                UserAccount,
                user.user_id(),
                'buzz_credentials').get()
        http = httplib2.Http()
        http = credentials.authorize(http)
        service = build("buzz", "v1", http=http)
        activities = service.activities()
 
        shout = Shout(message=message)
        shout.put()
        new_activity_body = {
                'title': 'Testing insert',
                'object': {'content': shout.message, 'type': 'note'}
                }
        activity = activities.insert(
                userId='@me',
                body=new_activity_body).execute()

class BuzzOAuthHandler(webapp.RequestHandler):
    @login_required
    def get(self):
      user = users.get_current_user()
      logging.info('user id: %s' % user.user_id())
      flow = pickle.loads(memcache.get('buzz' + user.user_id()))
      if flow:
          logging.info(self.request.params)
          credentials = flow.step2_exchange(self.request.params)
          StorageByKeyName(
                  UserAccount,
                  user.user_id(),
                  'buzz_credentials').put(credentials)
          self.redirect("/authorization")
      else:
          logging.warning('authorization failed')

